<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Helpers\SortHelper;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Mapper\ChCustomerServiceMapper;
use App\CustHub\Model\ChWord;
use App\CustHub\Model\ChWordGroup;
use App\CustHub\Request\WordGroupRequest;
use App\CustHub\Request\WordRequest;
use App\CustHub\Service\WordGroupService;
use App\CustHub\Service\WordService;
use App\Enum\WordTypeEnum;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\CustHub\Service\ChUserService;
use Hyperf\Di\Annotation\Inject;

#[Controller(prefix: 'ch/word'),ApiAuth,VerifySignature]
class WordController extends BaseController
{
    #[Inject]
    protected ChUserService $service;

    #[Inject]
    protected WordService $wordService;

    #[Inject]
    protected WordGroupService $wordGroupService;


    #[Inject]
    protected ChCustomerServiceMapper $customerServiceMapper;

    /**
     * 添加话术分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/add'),ChPermission('ch:word:group:add')]
    public function addGroup(WordGroupRequest $request)
    {
        return $this->wordGroupService->save($request->all()) ? $this -> success('添加成功') : $this -> error('添加失败');
    }

    /**
     * 修改话术分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/edit'),ChPermission('ch:word:group:edit')]
    public function editGroup(WordGroupRequest $request)
    {
        return $this->wordGroupService->update($request->input('id'),$request->all()) ? $this -> success('操作成功') : $this -> error('操作失败');
    }

    #[PostMapping('group/delete'),ChPermission('ch:word:group:delete')]
    public function deleteGroup(WordGroupRequest $request)
    {
        $this->wordGroupService->delGroup($request->all());
        return $this -> success('删除成功',[]);
    }


    /**
     * 分组列表
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/list'),ChPermission('ch:word:group:list')]
    public function groupList()
    {
        $uid =$this->request->input('uid');
        $is_personal =$this->request->input('is_personal',0);
        $page_size =$this->request->input('page_size',15);
        $mainUid = $this->request->input('main_uid');

        if($is_personal == 1){
            $page = ChWordGroup::query() -> where('uid',$uid) -> where('p_id',0) -> where('is_personal',1) -> orderByDesc('sort') -> paginate((int)$page_size);
        }else{
            $page = ChWordGroup::query() -> where('main_uid',$mainUid)-> where('is_personal',0) -> where('p_id',0) -> orderByDesc('sort') -> paginate((int)$page_size);
        }
        foreach ($page as &$item){
            $has_group = false;
            if(ChWord::query() -> where('group_id',$item -> id) -> count() > 0){
                $has_group = true;
            }
            $child = [];
            $p_id = $item -> pid;
            if($p_id == 0){
                $child = ChWordGroup::query() -> where('p_id',$item -> id) -> get();
            }
            $item['child'] = $child;
            $item['has_group'] = $has_group;
        }
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }

    /**
     * @direction
     * down    下移
     * up      上移
     * top     置顶
     * bottom  置底
     * exchange  交换
     * 排序
     */
    #[PostMapping('group/sort'),ChPermission('ch:word:group:sort')]
    public function sortGroup()
    {
        $this -> validateParam([
            'direction' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $direction =$this->request->input('direction');
        $id =$this->request->input('id');
        $otherId =$this->request->input('other_id');
        $isPersonal = ChWordGroup::query() ->  where('id',$id) -> value('is_personal');
        $mainUid = $this->request->input('main_uid');
        if($isPersonal == 1){
            $where = [
                ['uid', '=', $uid],
                ['p_id', '=', 0],
                ['is_personal','=',1]
            ];
            $field = 'main_sort';
        }else{
            $where = [
                ['main_uid', '=', $mainUid],
                ['p_id', '=', 0],
                ['is_personal','=',0]
            ];
            $field = 'sort';
        }
        $sortHelper = new SortHelper(ChWordGroup::class,$where);
        $sortHelper -> process($direction,$id,$otherId);
        return $this -> success('操作成功');
    }



    /**
     * 添加话术
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('add'),ChPermission('ch:word:add')]
    public function add(WordRequest $request)
    {
        return $this->wordService->save($request->all()) ? $this -> success('添加成功') : $this -> error('添加失败');
    }

    /**
     * 修改话术
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('edit'),ChPermission('ch:word:edit')]
    public function edit(WordRequest $request)
    {
        return $this->wordService->update($request->input('id'),$request->all()) ? $this -> success('操作成功') : $this -> error('操作失败');
    }


    /**
     * 话术列表
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('list'),ChPermission('ch:word:list')]
    public function list()
    {
        $params = $this -> request -> all();
        $uid =$this->request->input('uid');
        $page_size =$this->request->input('page_size',15);
        $mainUid = $this->request->input('main_uid');
        $isPersonal =$this->request->input('is_personal',0);
        $groupId =$this->request->input('group_id');
        $csId = $this->request->input('cs_id');

        if($isPersonal == 1){
            $where = [
                ['uid', '=', $uid],
                ['is_personal','=',1]
            ];

            if($csId){
                $where[] = ['cs_id','=',$csId];
            }

            $field = 'sort';
        }else{
            $where = [
                ['main_uid', '=', $mainUid],
                ['is_personal','=',0]
            ];
            $field = 'main_sort';
        }
        if(not_empty($groupId)){
            $where[]= ['group_id', '=', $groupId];
        }
        if(!empty($params['keyword'])){
            $where[] = ['title','like',"%".$params['keyword']."%"];
        }
        if(!empty($params['msg_type'])){
            $where[] = ['msg_types','like',"%".$params['msg_type']."%"];
        }
        $page = ChWord::query() -> with(['group' => function($q){
            $q ->  select('id','title','p_id');
        }]) ->where($where) -> orderByDesc($field) -> paginate((int)$page_size);
        $data = [
            'items' => $page -> items(),
            'pageInfo' => [
                'total' => $page->total(),
                'currentPage' => $page->currentPage(),
                'totalPage' => $page->lastPage(),
            ],
        ];
        return $this -> success('获取成功',$data);
    }


    #[PostMapping('sort'),ChPermission('ch:word:sort')]
    public function sort()
    {
        $this -> validateParam([
            'direction' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $direction =$this->request->input('direction');
        $mainUid = $this->request->input('main_uid');
        $id =$this->request->input('id');
        $otherId =$this->request->input('other_id');
        $is_personal = ChWord::query() ->  where('id',$id) -> value('is_personal');
        if($is_personal == 1){
            $where = [
                ['uid', '=', $uid],
                ['is_personal','=',1],
            ];
            $field = 'sort';
        }else{
            $where = [
                ['main_uid', '=', $mainUid],
                ['is_personal','=',0],
            ];
            $field = 'main_sort';
        }

        $sortHelper = new SortHelper(ChWord::class,$where,$field);
        $sortHelper -> process($direction,$id,$otherId);
        return $this -> success('操作成功');
    }


    #[PostMapping('delete'),ChPermission('ch:word:delete')]
    public function delete()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $idStr =$this->request->input('id');
        $ids=explode(",",$idStr);
        ChWord::query() -> whereIn('id',$ids) -> delete();
        return $this -> success('删除成功',[]);
    }


    /**
     * 复制
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('copy'),ChPermission('ch:word:copy')]
    public function copy(WordRequest $request)
    {
        return $this->wordService->copy($request->all()) ?  $this -> success('复制成功') : $this -> error('复制失败');
    }


    /**
     * 详情
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('detail'),ChPermission('ch:word:detail')]
    public function detail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $id =$this->request->input('id');
        $data = ChWord::query() ->with(['group' => function($q){
            $q ->  select('id','title','p_id');
        }]) -> where('id',$id) -> first();

        $csInfo = $this->customerServiceMapper->findById($data->cs_id);
        $data['cs_info'] = $csInfo;
        return $this -> success('复制成功',$data);
    }

    #[PostMapping('types')]
    public function getTypes()
    {
        $types = WordTypeEnum::getList();
        return $this -> success($types);

    }
}